package Offer.offer2017;

import domain.ListNode;

/**
 * 一个排序的链表中，存在重复的结点
 * Created by 雷文康 on 2018/1/10.
 */
public class DeleteDuplicationNode {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(4);
        ListNode node6 = new ListNode(4);
        ListNode node7 = new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;

        ListNode newHead = deleteDuplicationNode(head);
        ListNode p = newHead;
        while (p != null){
            System.out.println(p.val);
            p = p.next;
        }

    }

    public static ListNode deleteDuplicationNode(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode first = new ListNode(-1);
        first.next = head;

        ListNode p = head;
        ListNode pre = first;

        while (p != null && p.next != null){
            if (p.val == p.next.val){
                int val = p.val;
                while (p != null && p.val == val){
                    p = p.next;
                }
                pre.next = p;
            } else {
                pre = p;
                p = p.next;
            }
        }
        return first.next;
    }
}
